package cn.ycc1.boot3ftp.service;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author ycc
 * @date 2023/11/26
 */
@Service
public class FtpService {

//    private String server = "ftp.example.com";
//    private int port = 21;
//    private String user = "username";
//    private String pass = "password";
    @Value("${ftp.host}")
    private String host;

    @Value("${ftp.port}")
    private int port;

    @Value("${ftp.username}")
    private String username;

    @Value("${ftp.password}")
    private String password;

    public void uploadFile(String filePath) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            FileInputStream inputStream = new FileInputStream(filePath);
            String remoteFileName = Paths.get(filePath).getFileName().toString();
            boolean done = ftpClient.storeFile(remoteFileName, inputStream);
            inputStream.close();
            if (done) {
                System.out.println("The file was uploaded successfully.");
            } else {
                System.out.println("Failed to upload the file.");
            }
        } finally {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
    }
}
